package com.fulei.logic;

import com.bjfl.saleManager.util.HexByteDumper;
import com.bjfl.saleManager.util.LogUtil;
import com.dwin.navy.serialportapi.SerailPortOpt;
import com.bjfl.bean.GoodsLineMsg;
import com.log.LatteLogger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GoodsOperate {
    private static SerailPortOpt serialPort = null;
    //com指令
    public static String comNo = "";
    public static String baudRate = "";

    public static boolean OpenPort() {
        try {
            serialPort = new SerailPortOpt();

            serialPort.mDevNum = Integer.parseInt(comNo);
            serialPort.mSpeed = Integer.parseInt(baudRate);
            serialPort.mDataBits = 8;
            serialPort.mStopBits = 1;
            serialPort.mParity = 110;
            if (serialPort.mFd == null) {
                serialPort.openDev(serialPort.mDevNum);
                serialPort.setSpeed(serialPort.mFd, serialPort.mSpeed);
                serialPort.setParity(serialPort.mFd, serialPort.mDataBits, serialPort.mStopBits, serialPort.mParity);
            }
        } catch (Exception ex) {
            LogUtil.writeExceptionLog(ex.getMessage());
        }
        return true;
    }

    public static void closeSerialPort() {
        try {
            if (serialPort.mFd != null) {
                serialPort.closeDev(serialPort.mFd);
            }
            serialPort.mFd = null;
            serialPort = null;
        } catch (Exception ex) {
            LogUtil.writeExceptionLog(ex.getMessage());
        }
    }

    public static int goodsReset() {
        int return_data = 0;
        try {
            initSerialPort();
            byte[] SendData = new byte[9];
            SendData[0] = 90;
            SendData[1] = 78;
            SendData[2] = -128;
            SendData[3] = 0;
            SendData[4] = 1;
            SendData[5] = 1;
            SendData[6] = -99;

            SendData[7] = 90;
            SendData[8] = 83;

            LogUtil.writeGoodsDeviceLog("goodsReset:" + LogUtil.bytesToHexString(SendData, SendData.length));
            if (null != serialPort.mFd) {
                serialPort.writeBytes(SendData);
            }
            Thread.sleep(200L);


            byte[] ReadData = new byte[512];
            int ReadDataLength = serialPort.readBytes(ReadData, 10, 28);
            if (ReadDataLength < 10) {
                return -1;
            }
            LogUtil.writeGoodsDeviceLog("goodsReset:" + LogUtil.bytesToHexString(ReadData, ReadDataLength));
            return_data = 1;
        } catch (Exception ex) {
            LogUtil.writeExceptionLog("goodsReset 异常:" + ex.getMessage());
            return_data = -1;
        }
        return return_data;
    }

    public static String goodsRangeCheckOpenDoor(byte address, int lineNum) {
        String returnData = "";
        try {
            initSerialPort();
            byte[] sendData = sendCmdData(address, (byte) 0x2);

            LogUtil.writeGoodsDeviceLog("goodsRangeCheckOpenDoor Send:" +
                    LogUtil.bytesToHexString(sendData, sendData.length));
            LatteLogger.d("OpenSend：",LogUtil.bytesToHexString(sendData, sendData.length));
            if (null != serialPort.mFd) {
                serialPort.writeBytes(sendData);
            }
            Thread.sleep(200L);

            byte[] readData = new byte[28];
            int ReadDataLength = serialPort.readBytes(readData, 200, 28);
            if (ReadDataLength < 10) {
                return "";
            }

            LogUtil.writeGoodsDeviceLog(
                    "goodsRangeCheckOpenDoor Read:" + LogUtil.bytesToHexString(readData, ReadDataLength));

            //5A 4E
            // 05  层数
            // 01 14
            // 0100 0000 0000 0000 0000 0000 0000 0000 0000 0000
            // 0C 5A53

            //5A4E 05 01 14 0000000000000000000000000000000000000000 0D 5A53
            LatteLogger.e("OpenDoor Read", LogUtil.bytesToHexString(readData, ReadDataLength));
            if ((readData[0] == 90) && (readData[1] == 78) &&
                    (readData[26] == 90) && (readData[27] == 83) &&
                    (calculateXORSum(readData, 0, 28) == 0)) {
                byte[] copyArr = new byte[20];

                for (int j = 0; j < 20; j++) {
                    copyArr[j] = readData[(5 + j)];
                }
                returnData = sumGoodsNum(readData[2], copyArr, lineNum);
            }
        } catch (Exception ex) {
            LogUtil.writeExceptionLog("goodsRangeCheckOpenDoor 异常:" + ex.getMessage());
            returnData = "";
        }
        LatteLogger.e("ThreeGoOpen", returnData);
        return returnData;
    }

    public static String goodsRangeCheckCloseDoor(byte address, byte dataCmd, String userScanId, int lineNum) {
        String returnData = "";
        try {
            initSerialPort();
            byte[] sendData = sendCmdData(address, dataCmd);
            LogUtil.writeGoodsDeviceLog("goodsRangeCheckCloseDoor Send:   " + userScanId + "   " +
                    LogUtil.bytesToHexString(sendData, sendData.length));
            if (null != serialPort.mFd) {
                serialPort.writeBytes(sendData);
            }

            Thread.sleep(200L);
            byte[] readData = new byte[28];
            int readDataLength = serialPort.readBytes(readData, 100, 28);

            if (readDataLength < 10) {
                return "";
            }

            LogUtil.writeGoodsDeviceLog(
                    "goodsRangeCheckCloseDoor Read:   " + userScanId + "   " +
                            LogUtil.bytesToHexString(readData, readDataLength));
            LatteLogger.e("closeDoor Read", LogUtil.bytesToHexString(readData, readDataLength));

            //5A 4E 包头
            // 05 层数
            // 01 发送主机地址
            // 14 长度
            // 00 00   00 00   00 00   00 00   00 00   00 00   00 00   00 00   00 00   00 00
            // 0D 校验位
            // 5A 53  包尾

            if ((readData[0] == 90) && (readData[1] == 78) &&
                    (readData[26] == 90) && (readData[27] == 83) &&
                    (calculateXORSum(readData, 0, 28) == 0)) {
                byte[] copyArr = new byte[20];

                for (int j = 0; j < 20; j++) {
                    copyArr[j] = readData[(5 + j)];
                }
                returnData = sumGoodsNum(readData[2], copyArr, lineNum);

            }
        } catch (Exception ex) {

            LogUtil.writeExceptionLog("checkScaler接口异常:" + ex.getMessage());
            returnData = "";
        }
        LatteLogger.e("ThreeGoClose", returnData);
        return returnData;
    }

    public static String sumGoodsNum(byte address, byte[] returnNum, int lineNum) {
        String returnData = "";
        int[] buf_data = new int[lineNum];
        int j = 0;
        try {
            for (int i = 0; i < lineNum; i++) {
                buf_data[i] = ((returnNum[j] & 0xff) << 8 & 0xFF00);
                j++;
                buf_data[i] = (returnNum[j] & 0xFF | buf_data[i]);
                j++;
                buf_data[i] = (buf_data[i] * 10 / 36);

                if (address > 9) {
                    returnData = returnData + address + "00" + (i + 1) + "," + buf_data[i] + "|";
                } else {
                    returnData = returnData + "0" + address + "00" + (i + 1) + "," + buf_data[i] + "|";
                }
            }
            LogUtil.writeGoodsDeviceLog("货物信息 加工后的信息:" + returnData);

        } catch (Exception ex) {
            LogUtil.writeExceptionLog("sumGoodsNum 异常:" + ex.getMessage());
            returnData = "";
        }
        return returnData;
    }

    public static byte calculateXORSum(byte[] b, int startIndex, int len) {
        byte xor = 0;
        for (int i = 0; i < len; i++) {
            xor = (byte) (xor ^ b[(startIndex + i)]);
        }
        return xor;
    }

    public static String getStringFromData(byte[] data, int start, int len) {
        byte[] bts = new byte[len];
        System.arraycopy(data, start, bts, 0, len);
        return HexByteDumper.toStringHex(HexByteDumper.getHexDump(bts));
    }

    public static byte[] sendCmdData(byte address, byte cmd) {
        byte[] sendData = new byte[9];
        try {
            byte tmp = 90;
            sendData[0] = 90;
            sendData[1] = 78;
            sendData[2] = address;
            sendData[3] = 0;
            sendData[4] = 1;
            sendData[5] = cmd;
            sendData[6] = 0;
            sendData[7] = 90;
            sendData[8] = 83;
            for (int i = 0; i < 8; i++) {
                tmp = (byte) (tmp ^ sendData[(i + 1)]);
            }
            sendData[6] = tmp;
        } catch (Exception ex) {
            LatteLogger.e("sendCmdData", ex.getMessage());
            LogUtil.writeExceptionLog("sendCmdData:" + ex.getMessage());
        }
        return sendData;
    }

    public static String getGoodsLineState(byte layer) {
        String returnData = "";
        try {
            initSerialPort();
            byte[] sendData = sendCmdData(layer, (byte) 0x04);

            LatteLogger.e("goodsRangeCheckGoodsLine Send:",
                    LogUtil.bytesToHexString(sendData, sendData.length));
            if (null != serialPort.mFd) {
                serialPort.writeBytes(sendData);
            }
            Thread.sleep(200L);


            byte[] readData = new byte[512];
            int ReadDataLength = serialPort.readBytes(readData, 10, 28);
            if (ReadDataLength < 10) {
                return "";
            }
            returnData = LogUtil.bytesToHexString(readData, ReadDataLength);
            LatteLogger.e("LineMsg Read", returnData);
        } catch (Exception ex) {
            ex.printStackTrace();
            LatteLogger.e("Line", ex.getMessage());
            returnData = "";
        }
        return returnData;
    }

    private static void initSerialPort() {
        if (serialPort == null) {
            OpenPort();
        }
        if (serialPort.mFd == null) {
            serialPort.openDev(serialPort.mDevNum);
            serialPort.setSpeed(serialPort.mFd, serialPort.mSpeed);
            serialPort.setParity(serialPort.mFd, serialPort.mDataBits, serialPort.mStopBits, serialPort.mParity);
        }
    }

    public static List<GoodsLineMsg> getGoodsLineMsgWithSingle(byte layer, byte cmdType, String userScanId,
                                                               int lineNum) {
        List<GoodsLineMsg> goodsLineMsgList = new ArrayList<>();
        try {
            initSerialPort();
            byte[] sendData = sendCmdData(layer, cmdType);

            LogUtil.writeGoodsDeviceLog("goodsRangeCheckCloseDoor Send:   " + userScanId + "   " +
                    LogUtil.bytesToHexString(sendData, sendData.length));
            if (null != serialPort.mFd) {
                serialPort.writeBytes(sendData);
            }
            Thread.sleep(200L);

            byte[] readData = new byte[28];
            int readDataLength = serialPort.readBytes(readData, 200, 28);

            if (readDataLength < 10) {
                return Collections.EMPTY_LIST;
            }

            LogUtil.writeGoodsDeviceLog(
                    "goodsRangeCheckCloseDoor Read:   " + userScanId + "   " +
                            LogUtil.bytesToHexString(readData, readDataLength));
            LatteLogger.e("closeDoor Read", LogUtil.bytesToHexString(readData, readDataLength));
            //5A 4E 包头
            // 05 层数
            // 01 发送主机地址
            // 14 长度
            // 00 00   00 00   00 00   00 00   00 00   00 00   00 00   00 00   00 00   00 00
            // 0D 校验位
            // 5A 53  包尾
            if ((readData[0] == 90) && (readData[1] == 78) &&
                    (readData[26] == 90) && (readData[27] == 83) &&
                    (calculateXORSum(readData, 0, 28) == 0)) {
                byte[] copyArr = new byte[20];

                for (int j = 0; j < 20; j++) {
                    copyArr[j] = readData[(5 + j)];
                }
                goodsLineMsgList = sumGoodsNumWithObject(readData[2], copyArr, cmdType, lineNum);
            }
        } catch (Exception ex) {

            LogUtil.writeExceptionLog("checkScaler接口异常:" + ex.getMessage());
            return Collections.EMPTY_LIST;
        }
        return goodsLineMsgList;
    }

    private static List<GoodsLineMsg> sumGoodsNumWithObject(byte layer, byte[] returnNum, byte cmdType,
                                                            int lineNum) {
        List<GoodsLineMsg> goodsLineMsgList = new ArrayList<>();
        int[] buf_data = new int[lineNum];
        int j = 0;
        try {
            for (int i = 0; i < lineNum; i++) {

                buf_data[i] = ((returnNum[j] & 0xff) << 8 & 0xFF00);
                j++;
                buf_data[i] = (returnNum[j] & 0xFF | buf_data[i]);
                j++;
                buf_data[i] = (buf_data[i] * 10 / 36);
                if (buf_data[i] != 0) {
                    GoodsLineMsg goodsLineMsg = new GoodsLineMsg();
                    if (layer > 9) {
                        goodsLineMsg.setLayerNum(layer + "");

                    } else {
                        goodsLineMsg.setLayerNum("0" + layer);

                    }
                    goodsLineMsg.setLineNum("00" + (i + 1));
                    if (cmdType == 3) {
                        goodsLineMsg.setIsAddAction(GoodsLineMsg.BUY_GOODS);
                    } else {
                        goodsLineMsg.setIsAddAction(GoodsLineMsg.ADD_GOODS);
                    }
                    goodsLineMsg.setLayerAndLineNum(goodsLineMsg.getLayerNum() + goodsLineMsg.getLineNum());
                    goodsLineMsg.setLineLength(buf_data[i] + "");

                    goodsLineMsgList.add(goodsLineMsg);
                }


            }
            LogUtil.writeGoodsDeviceLog("货物信息 加工后的信息:" + goodsLineMsgList.toString());

        } catch (Exception ex) {
            LogUtil.writeExceptionLog("sumGoodsNum 异常:" + ex.getMessage());
            ex.printStackTrace();
            goodsLineMsgList = Collections.EMPTY_LIST;
        }

        return goodsLineMsgList;
    }
}
